<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Document extends BaseModel
{
    protected $guarded = [];

    protected $table = 'qh_documents';

    protected $appends = ['tags', 'had', 'collect', 'fileM', 'categoryIds'];

    protected $casts = [
        'previewImages' => 'json'
    ];

    public function tag(): BelongsToMany
    {
        return $this->belongsToMany(DocumentTag::class, 'qh_document_tag_relation', 'documentId', 'tagId');
    }

    public function category(): BelongsToMany
    {
        return $this->belongsToMany(DocumentCategory::class, 'qh_document_category_relation','documentId', 'categoryId');
    }

    public function getCategoryIdsAttribute(): array
    {
        return $this->category()->pluck('categoryId')->toArray();
    }

    public function getTagsAttribute()
    {
        if (request()->is('admin/*')) {
            return $this->tag()->pluck('name')->toArray();
        }
        return $this->tag;
    }

    public function getHadAttribute(): bool
    {
        if (\Auth::guard('api')->check()) {
            return \DB::table('qh_user_has_document')
                ->where('userId', \Auth::guard('api')->user()->id)
                ->where('documentId', $this->id)
                ->exists();
        }

        return false;
    }

    public function getCollectAttribute(): bool
    {
        if (\Auth::guard('api')->check()) {
            return \DB::table('qh_user_collect_document')
                ->where('userId', \Auth::guard('api')->user()->id)
                ->where('documentId', $this->id)
                ->exists();
        }

        return false;
    }

    public function getFileMAttribute(): float
    {
        $fileSize = $this->fileSize ?? 0;
        $m = $fileSize / 1024;
        return round($m, 2);
    }

    public function getPrintAttribute($v) {
        if (request()->is('admin/*')) return $v;
        return boolval($v);
    }
}
